package com.favorite;

import java.util.ArrayList;
import java.util.List;

public class Solution1319 {
    int[] father;
    public int makeConnected(int n, int[][] connections) {
        father = new int[n];
        for (int i = 0; i < n; i++) {
            father[i] = i;
        }
        int count = n;
        int extra = 0;
        for (int i = 0; i < connections.length; i++) {
            if (same(connections[i][0], connections[i][1])) extra++;
            else {
                join(connections[i][0], connections[i][1]);
                count--;
            }
        }
        if (count - 1 > extra) return -1;
        return count - 1;
    }

    public int find(int x) {
        if (x == father[x]) {
            return x;
        }
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}
